package com.yao.config;

import com.yao.annotation.Component;
import com.yao.test.YamlTest;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/2/14 12:50
 * FileName: AnnotateSpringConfig
 * Description:
 */
public class AnnotateSpringConfig implements ISpringConfig{
    public static String classpathRoot="";
    static {
        String path = YamlTest.class.getResource("/").getPath();
//        System.out.println(path.replace("/","\\").substring(1));
        classpathRoot=path.replace("/","\\").substring(1);
    }
    public static void listDirectory(File directory){
        if(directory.isDirectory()){
            File[] files = directory.listFiles();
            for (File subfile : files) {
                if(subfile.isFile()){
                    processClassFile(subfile);
                }else{
                    listDirectory(subfile);
                }
            }
        }else{
            processClassFile(directory);
        }
    }

    public static void processClassFile(File file ){
        if(file.getName().endsWith(".class")) {
//            System.out.println(file.getName());
//            System.out.println(file.getPath());
//            System.out.println(file.getAbsolutePath());
            String substring = file.getPath().substring(classpathRoot.length());
            substring = substring.substring(0,substring.length()-6);
            String classWithPackage = substring.replace("\\", ".");
//            System.out.println(classWithPackage);
            try {
                Class<?> aClass = Class.forName(classWithPackage);
                System.out.println(aClass);
                System.out.println(aClass.getAnnotation(Component.class));
                if (aClass.isAnnotationPresent(Component.class)) {
                    System.out.println(true);
                    processComponent(aClass);
                }
//                System.out.println(Class.forName(classWithPackage));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void processComponent(Class cls){
        try {
            Object o = cls.getDeclaredConstructor().newInstance();
            System.out.println(o);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void config() {
        System.out.println("注解配置");
        File file = new File(YamlTest.class.getResource("/").getPath());
        listDirectory(file);
    }
}
